package com.bw.Controller;

import com.bw.common.BResult;
import com.bw.config.MyTaskExecutorConfig;
import com.bw.domain.Good;
import com.bw.domain.Take;
import com.bw.service.GoodService;
import com.bw.service.TakeService;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class TakeController {
    @Autowired
    MyTaskExecutorConfig myTaskExecutorConfig;
    @Autowired
    TakeService takeService;
    @Autowired
    GoodService goodService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @RequestMapping("getAdd")
    public void getAdd(){
        for (int i = 0; i <5 ; i++) {
            myTaskExecutorConfig.myTaskExecutor().execute(() -> {
                     takeService.save(Take.builder().status(0).goodId(1).startTime(new Date()).build());
            });
        }

    }
    @RequestMapping("getlist")
    public void getlist(){
        List<Good> list = goodService.list();
        for (Good good : list) {
            redisTemplate.opsForValue().set("stock:"+good.getId(),good.getStoke());
        }

    }
    @RequestMapping("showlist")
    public BResult showlist(Integer goodId,Integer qsId) throws InterruptedException {
        Take take = takeService.getById(goodId);
        Integer status = take.getStatus();
        if (status==0){
            RLock   lock = redissonClient.getLock("waimai:" + goodId);
            try {

                boolean b = lock.tryLock(3, TimeUnit.SECONDS);
                if (b){
                    Take take1 = takeService.getById(goodId);
                    Integer status1 = take1.getStatus();
                    if (status1==0) {
                        Long decrement = redisTemplate.opsForValue().decrement("stock:" + goodId, 1);
                        if (decrement >= 0) {
                            take.setStatus(1);
                            take.setQsId(qsId);
                            takeService.updateById(take);
                            return BResult.success("恭喜你抢到订单");

                        }
                    }

                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }

        return  BResult.error("手慢无");

    }
}
